package com.kingyea.mobilepolice.apimanage.accesscontrol.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

/**
 * @author chenjw
 * @version v1.0.0
 * @description
 * @date Created in 2018/4/4 10:17
 */

public class RecordableCounter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RecordableCounter.class);

    private final String preferenceKey;

    private final Preferences preferences;

    private final boolean running = false;

    /**
     * 复位计数器定时器
     **/
    java.util.Timer timer = new java.util.Timer(true);

    public RecordableCounter(final Preferences preferences, final String preferenceKey, final String pathName) {
        this.preferences = preferences;
        this.preferenceKey = preferenceKey;
        final long n = preferences.getLong(preferenceKey, 0L);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("key=" + preferenceKey + ",offline count=" + n);
        }
        InvocationCount.atomicMap.put(pathName + this.preferenceKey, n);
        if (!this.running) {
            this.putPreferencesThread(pathName);
        }
    }

    public void inc(final String pathName) {
        final long n = InvocationCount.atomicMap.incrementAndGet(pathName + this.preferenceKey);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("set %s=%d", this.preferenceKey, n));
        }
        // this.putPreferences(n);
    }

    private void putPreferences(final long n) {
        this.preferences.putLong(this.preferenceKey, n);
        try {
            this.preferences.flush();
        } catch (final BackingStoreException e) {
            LOGGER.warn("当前调用次数保存失败", e);
        }
    }

    public void reset(final String pathName) {
        InvocationCount.atomicMap.put(pathName + this.preferenceKey, 0L);
        this.putPreferences(0L);
    }

    public long getCount() {
        return this.preferences.getLong(this.preferenceKey, 0L);
    }

    public void putPreferencesThread(final String pathName) {
        this.timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                final Long n = InvocationCount.atomicMap.get(pathName + RecordableCounter.this.preferenceKey);
                RecordableCounter.this.putPreferences(n);
            }
        }, 0, 2 * 1000);
    }

}
